<template>
  <div :class="prefixCls" style="z-index: 1">
    <Popover
      title=""
      trigger="click"
      :overlayClassName="`${prefixCls}__overlay`"
      @click="handleClick"
      v-model:visible="visible"
    >
      <Badge :count="count" dot :numberStyle="numberStyle">
        <BellOutlined />
      </Badge>
      <template #content>
        <div v-if="listData.length > 0">
          <Tabs>
            <template v-for="item in listData" :key="item.key">
              <TabPane>
                <template #tab>
                  {{ item.name }}
                  <span v-if="item.list.length !== 0">({{ item.list.length }}条)</span>
                </template>
                <!-- 绑定title-click事件的通知列表中标题是“可点击”的-->
                <NoticeList
                  :list="item.list"
                  v-if="item.key === '1'"
                  @title-click="onNoticeClick"
                />
                <NoticeList :list="item.list" v-else />
              </TabPane>
            </template>
            <template #rightExtra>
              <Tooltip title="将消息置为已读"
                ><span class="cursor-pointer mr-6 text-blue-400" @click="handleRead(listData)"
                  >已读</span
                ></Tooltip
              >
              <span v-if="countdown > 0">({{ countdown }}秒)</span>
              <CloseOutlined class="ml-2 cursor-pointer" style="color: #f00" @click="handleClose" />
            </template>
          </Tabs>
          <div class="mt-2 flex justify-center cursor-pointer" @click="toMessage">更多 </div>
        </div>
        <div v-else class="flex justify-center">无</div>
      </template>
    </Popover>
    <MessageCenterInfoDrawer @register="registerDrawer" />
  </div>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, onMounted, onUnmounted } from 'vue';
  import { Popover, Tabs, Badge, Tooltip } from 'ant-design-vue';
  import { BellOutlined, CloseOutlined } from '@ant-design/icons-vue';
  import { ListItem } from './data';
  import NoticeList from './NoticeList.vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  // import { useMessage } from '/@/hooks/web/useMessage';
  import { getNewMsgsOfUser, getOnlineNotify, batchRead } from '/@/api/workOffice/workOffice';
  import { useDrawer } from '/@/components/Drawer';
  import MessageCenterInfoDrawer from '/@/views/pages/workOffice/messageCenter/messageCenterInfoDrawer.vue';
  import { getToken } from '/@/utils/auth';
  import { useUserStore } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGo } from '/@/hooks/web/usePage';
  export default defineComponent({
    components: {
      Popover,
      BellOutlined,
      Tabs,
      TabPane: Tabs.TabPane,
      Badge,
      NoticeList,
      MessageCenterInfoDrawer,
      CloseOutlined,
      Tooltip,
    },
    setup() {
      const userStore = useUserStore();
      const { prefixCls } = useDesign('header-notify');
      // const { createMessage } = useMessage();
      const listData = ref<any>([]);
      const visible = ref(false);
      const oldIds = ref('');
      const countdown = ref(0);
      const setCountdown = () => {
        countdown.value = 5;
        const timer = setInterval(() => {
          if (countdown.value <= 1) {
            countdown.value = 0;
            clearInterval(timer);
            visible.value = false;
          } else {
            countdown.value -= 1;
          }
        }, 1000);
      };
      const { createMessage } = useMessage();

      let sintNewMsg, sintOnline;
      onMounted(() => {
        getNewMsg();

        const serverInfo = userStore.getServerInfo;
        const refreshMessage = serverInfo.refreshMessage;
        const refreshOnlineUserNotify = serverInfo.refreshOnlineUserNotify;

        sintNewMsg = setInterval(() => {
          if (getToken() == undefined) {
            window.clearInterval(sintNewMsg);
          } else {
            getNewMsg();
          }
        }, refreshMessage * 1000);

        // sintOnline = setInterval(() => {
        //   if (getToken() == undefined) {
        //     window.clearInterval(sintOnline);
        //   } else {
        //     getOnlineNotify();
        //   }
        // }, refreshOnlineUserNotify * 1000);
      });

      onUnmounted(() => {
        if (sintNewMsg) window.clearInterval(sintNewMsg);
        if (sintOnline) window.clearInterval(sintOnline);
      });

      function handleClick() {
        // getNewMsg();
      }
      function getNewMsg() {
        listData.value = [];
        getNewMsgsOfUser().then((res) => {
          if (res && res.length > 0) {
            let data = res.map((item) => {
              item.avatar = '';
              item.description = '';
              item.datetime = item.sendTime;
              // item.type = '1';
              return item;
            });
            const ids = data.map((item) => item.id).join(',');
            if (ids != oldIds.value) {
              visible.value = true;
              oldIds.value = ids;
              setCountdown();
            }
            listData.value.push({
              key: '1',
              name: '消息',
              list: data,
            });
          }
        });
      }
      const go = useGo();
      //跳转
      function toMessage() {
        go('/messageCenter');
      }
      const [registerDrawer, { openDrawer }] = useDrawer();
      function handleView(record: any) {
        console.log('handleView record', record);
        if (record.type == 1) {
          go({
            path: '/internalEmail',
            query: {
              op: 'show',
              curRecord: JSON.stringify(record),
            },
          });
        } else {
          openDrawer(true, {
            isUpdate: true,
            record,
          });
        }
      }
      const count = computed(() => {
        let count = 0;
        for (let i = 0; i < listData.value.length; i++) {
          count += listData.value[i].list.length;
        }
        return count;
      });

      function onNoticeClick(record: ListItem) {
        // createMessage.success('你点击了通知，ID=' + record.id);
        // 可以直接将其标记为已读（为标题添加删除线）,此处演示的代码会切换删除线状态
        record.titleDelete = !record.titleDelete;
        handleView(record);
        getNewMsg();
      }

      function handleClose() {
        visible.value = false;
      }

      async function handleRead(listData) {
        console.log('handleRead list', listData);
        const aryId = listData[0].list.map((item) => item.id);
        let ids = aryId.join(',');
        console.log('handleRead ids', ids);
        await batchRead({ ids: ids });
        createMessage.success('操作成功');
        listData[0].list = [];
        handleClose();
      }

      return {
        prefixCls,
        listData,
        count,
        onNoticeClick,
        numberStyle: {},
        registerDrawer,
        handleClick,
        toMessage,
        visible,
        countdown,
        handleClose,
        handleRead,
      };
    },
  });
</script>
<style lang="less">
  @prefix-cls: ~'@{namespace}-header-notify';

  .@{prefix-cls} {
    padding-top: 2px;
    &__overlay {
      max-width: 360px;
      min-width: 300px;
      z-index: 1000;
    }
    .ant-tabs-content {
      width: 300px;
    }

    .ant-badge {
      font-size: 18px;

      .ant-badge-multiple-words {
        padding: 0 4px;
      }

      svg {
        width: 0.9em;
      }
    }
  }
</style>
